package com.zhuiyun.project.api.video.publishVideo.service.impl;

import cn.hutool.core.io.FileUtil;
import com.zhuiyun.project.api.frontuser.entity.FrontUser;
import com.zhuiyun.project.api.frontuser.mapper.FrontUserMapper;
import com.zhuiyun.project.api.monitor.domain.server.Sys;
import com.zhuiyun.project.api.video.publishVideo.entity.Video;
import com.zhuiyun.project.api.video.publishVideo.mapper.PublishVideoMapper;
import com.zhuiyun.project.api.video.publishVideo.model.PublishVideoModel;
import com.zhuiyun.project.api.video.publishVideo.service.PublishVideoService;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.BeanUtils;
import com.zhuiyun.project.utils.UploadFileUtils;
import com.zhuiyun.project.utils.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import com.zhuiyun.project.utils.pageUtil.PageResult;
import com.zhuiyun.project.utils.uuid.IdUtils;
import com.zhuiyun.project.utils.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Transient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @ClassName PublishVideoServiceImpl
 * @Description 上传视频服务类 用于用户上传视频的增删改查
 * @Author qsh
 * @Date 2023/12/13 20:58
 **/
@Service
@Transactional
public class PublishVideoServiceImpl implements PublishVideoService {

    @Autowired
    private PublishVideoMapper publishVideoMapper;

    @Autowired
    private FrontUserMapper frontUserMapper;

    /**
     * @param publishVideoModel
     * @param pageRequest
     * @Author qsh
     * @Description 查询未推荐视频（运营
     * @Date 2023/12/14 20:03
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult getPublishVideo(PublishVideoModel publishVideoModel, PageRequest pageRequest) {
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        PageResult pageResult = MybatisPageHelper.getPageResult(publishVideoMapper.getPublishVideo(publishVideoModel));
        return CommonResult.ok(pageResult);
    }

    /**
    * @Author qsh
    * @Description 查询已推荐视频（运营
    * @Date 2024/2/23 9:42
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param publishVideoModel
* @param pageRequest
    */
    @Override
    public CommonResult getPublishVideoT(PublishVideoModel publishVideoModel, PageRequest pageRequest) {
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        PageResult pageResult = MybatisPageHelper.getPageResult(publishVideoMapper.getPublishVideoT(publishVideoModel));
        return CommonResult.ok(pageResult);
    }

    /**
    * @Author qsh
    * @Description 查询已下架视频（运营
    * @Date 2024/2/23 9:42
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param publishVideoModel
* @param pageRequest
    */
    @Override
    public CommonResult getPublishVideoX(PublishVideoModel publishVideoModel, PageRequest pageRequest) {
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        PageResult pageResult = MybatisPageHelper.getPageResult(publishVideoMapper.getPublishVideoX(publishVideoModel));
        return CommonResult.ok(pageResult);
    }

    /**
    * @Author qsh
    * @Description 查询视频详情
    * @Date 2023/12/15 15:40
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param vId
    * @param pageRequest
    */
    @Override
    public CommonResult getPublishVideoById(Integer vId, PageRequest pageRequest) {
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        Example example = new Example(Video.class);
        example.createCriteria().andEqualTo("vId", vId); // 设置要删除的记录的主键ID条件
        PageResult pageResult = MybatisPageHelper.getPageResult( publishVideoMapper.selectByExample(example));
        return CommonResult.ok(pageResult);
    }

    /**
    * @Author qsh
    * @Description 逻辑删除上传视频
    * @Date 2023/12/15 15:40
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param videoIds
    */
    @Override
    public CommonResult DeleteVideoById(List<Integer> videoIds) throws CommonException {
        // 验证参数的规范性
        if (ValidatorUtil.ValidationObject(videoIds)) {
            // 创建 Example 对象
            for (Integer vId : videoIds) {
                Example example = new Example(Video.class);
                example.createCriteria().andEqualTo("vId", vId); // 设置要删除的记录的主键ID条件
                List<Video> publishVideos = publishVideoMapper.selectByExample(example);
                for (Video publishVideo : publishVideos) {
                    if (publishVideo.getIsDelete() == 1) {
                        publishVideo.setIsDelete(0);
                    }else {
                        if (publishVideo.getBindVideo()==1 || publishVideo.getBindVideo()>1){
                            publishVideo.setBindVideo(0);
                        }
                        publishVideo.setIsDelete(1);
                    }
                    publishVideoMapper.updateByExampleSelective(publishVideo, example);
                }
            }
            return CommonResult.ok(EmErrorCode.DELETE_ERROR);
        } else {
            return CommonResult.ok(EmErrorCode.DELETE_ERROR);
        }
    }

    /**
    * @Author qsh
    * @Description 绑定视频池（推荐、取消推荐
    * @Date 2024/2/23 14:32
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param videoIds
    */
    @Override
    public CommonResult BindVideo(List<Integer> videoIds) throws CommonException {
        // 验证参数的规范性
        if (ValidatorUtil.ValidationObject(videoIds)) {
            // 创建 Example 对象
            for (Integer vId : videoIds) {
                Example example = new Example(Video.class);
                example.createCriteria().andEqualTo("vId", vId); // 设置要删除的记录的主键ID条件
                List<Video> publishVideos = publishVideoMapper.selectByExample(example);
                for (Video publishVideo : publishVideos) {
                    if (publishVideo.getBindVideo() == 1) {
                        publishVideo.setBindVideo(0);
                    }else {
                        publishVideo.setBindVideo(1);
                    }
                    publishVideoMapper.updateByExampleSelective(publishVideo, example);
                }
            }
            return CommonResult.ok(EmErrorCode.DELETE_ERROR);
        } else {
            return CommonResult.ok(EmErrorCode.DELETE_ERROR);
        }
    }

    /**
    * @Author qsh
    * @Description 上传视频封面
    * @Date 2023/12/18 10:01
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param file
    */
    @Override
    public CommonResult uploadVideoCover(MultipartFile file) throws CommonException {

        String uploadFiles =  UploadFileUtils.uploadFile(file);

        Integer uploadFileId = Integer.parseInt(uploadFiles);

        System.out.println("zzzzzzzzzzzz返回值"+uploadFileId);

        return CommonResult.ok(uploadFileId);
    }

    /**
    * @Author qsh
    * @Description 随机生成10位数字
    * @Date 2024/2/27 8:55
    * @Return java.lang.String
    * @param length
    */
    public static String generateRandomNumber(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; i++) {
            int digit = random.nextInt(10);
            sb.append(digit);
        }

        return sb.toString();
    }

    /**
    * @Author qsh
    * @Description 新增上传视频信息
    * @Date 2023/12/19 11:08
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param publishVideoModel
    */
    @Override
    public CommonResult saveVideo(PublishVideoModel publishVideoModel) throws CommonException {
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(publishVideoModel)){

            publishVideoModel.setIsDelete(1);
            publishVideoModel.setReviewStatus("已通过");
            publishVideoModel.setCreationTime(new Date());
            publishVideoModel.setAuditTime(new Date());
            String randomNum = generateRandomNumber(10);
            System.out.println("randomNumrandomNumrandomNumrandomNum"+randomNum);
            String vNumber = "sy_v"+randomNum;
            publishVideoModel.setVideoId(vNumber);

            Example example = new Example(FrontUser.class);
            example.createCriteria().andEqualTo("userAccount", publishVideoModel.getUserAccount()); // 设置要删除的记录的主键ID条件
            FrontUser fu = frontUserMapper.selectOneByExample(example);
            System.out.println("IDIDIDIDIDIDIDIDIDID"+fu.getId());
            publishVideoModel.setUserId(fu.getId());
            publishVideoModel.setBindVideo(0);
            publishVideoModel.setIdentifying("a");
            Video video = new Video();
            // publishVideoModel 对象拷贝成 video
            BeanUtils.copy(publishVideoModel, video);

            int i = publishVideoMapper.insert(video);
            if(i>0){
                return CommonResult.ok(EmErrorCode.SAVE_OK);
            }else{
                return CommonResult.ok(EmErrorCode.SAVE_ERROR);
            }
        }else{
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }

    /**
     * @Author qsh
     * @Description 编辑上传视频信息
     * @Date 2023/12/19 11:08
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param publishVideoModel
     */
    @Override
    public CommonResult updateVideo(PublishVideoModel publishVideoModel) throws CommonException {
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(publishVideoModel)){

            Example example = new Example(FrontUser.class);
            example.createCriteria().andEqualTo("userAccount", publishVideoModel.getUserAccount()); // 设置要删除的记录的主键ID条件
            FrontUser fu = frontUserMapper.selectOneByExample(example);
            System.out.println("IDIDIDIDIDIDIDIDIDID"+fu.getId());
            publishVideoModel.setUserId(fu.getId());

            Video video = new Video();
            // publishVideoModel 对象拷贝成 video
            BeanUtils.copy(publishVideoModel, video);
            Example example1 = new Example(Video.class);
            example1.createCriteria().andEqualTo("vId", video.getVId());
            int i = publishVideoMapper.updateByExampleSelective(video,example1);
            if(i>0){
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            }else{
                return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
            }
        }else{
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
    * @Author qsh
    * @Description 删除服务器视频
    * @Date 2023/12/25 14:31
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param id
    */
    @Override
    public CommonResult deleteV(Integer id) {
        return CommonResult.ok(UploadFileUtils.deleteFileById(id));
    }

    /**
     * @Author qsh
     * @Description 删除服务器视频封面
     * @Date 2023/12/25 14:31
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param id
     */
    @Override
    public CommonResult deleteVC(Integer id) {
        return CommonResult.ok(UploadFileUtils.deleteFileById(id));
    }
}
